<?php

namespace AppBundle\Controller\Admin;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Libs\Sms\Sms;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Pages;

class PageController extends BaseController
{
    /**
     * admin panel
     *
     */
    public function indexAction(Request $request)
    {
//        $user = $this->getUser();dump( $user);die;
        # render login page
        return $this->render('admin/index/index.html.twig');
    }

    /**
     * admin dashboard
     *
     */
    public function createAction(Request $request)
    {
        # render create page
        $em = $this->getDoctrine()->getManager();
        $categorys = $em->getRepository('AppBundle:Category')->findAll();

        # get page info
        $id = intval($request->get('id'));
        $page='';
        $images='';
        if($id){
            $page =  $em->getRepository('AppBundle:Pages')->findOneById($id);
            if($page){
                $temp = $page->getImages();
                $images = explode(';', $temp);
            }
        }
//   var_dump($page->getCategory());die;
        return $this->render('admin/page/create.html.twig',array('categorys'=>$categorys,'id'=>$id,'images'=>$images,'page'=>$page));
    }

    /**
     * upload file
     *
     */
    public function uploadAction(Request $request)
    {
        try {
            $file = $request->files->get('file');
            $fileName = $file->getClientOriginalName();
            $date = date("Ymd", time());
            $path = $this->getParameter('file_real_directory') . $date;
            $file->move($path, $fileName);

            $array = array(
                'errno' => 0,
                'path' => $this->getParameter('file_directory') . $date . '/' . $fileName,
            );
            return $this->json($array, 200);

        } catch (Exception $e) {
            return $this->json(array('errno' => 1), 400);
        }
    }

    /**
     * upload file
     *
     */
    public function deleteAction(Request $request)
    {
        try {
            $file = $request->get('file');
            if ($file && file_exists('.' . $file)) {
                unlink('.' . $file);
            }
            $array = array(
                'errno' => file_exists('.' . $file),
            );
            return $this->json($array, 200);
        } catch (Exception $e) {
            return $this->json(array('errno' => 1), 400);
        }
    }

    /**
     * make captcha.
     *
     * @param int width nullable the width of captcha image
     * @param int height nullable the height of captcha image
     */
    public function captchaAction(Request $request)
    {
        $width = intval($request->get('width')) ?: 150; // the width of captcha image
        $height = intval($request->get('height')) ?: 50; //the height of captcha image
        $length = 5; // captcha string length
        $no_effect = true; // ignore the line on image

        $pharse = new PhraseBuilder();
        $captcha = new CaptchaBuilder($pharse->build($length));
        $image = $captcha->setIgnoreAllEffects($no_effect)->build($width, $height)->get();

        $session = $request->getSession();
        $session->set('captcha', $captcha->getPhrase());

        $res = new Response($image);
        $res->headers->set('content-type', 'image/jpeg');

        return $res;
    }

    /**
     * send sms
     *
     * @param int phone require phonenumber
     * @param string code require the captcha code
     */
    public function sendSmsAction(Request $request)
    {
        $return['errno'] = 4;
        $return['message'] = "数据不全";

        $session = $request->getSession();
        $captcha = $session->get('captcha', '');
        $phone = intval($request->get('phone'));
        $code = $request->get('code');

        if ($phone && $code) {
            if ($code && $code == $captcha) {
                $return = send_verify_code($phone);
            } else {
                $return['errno'] = 5;
                $return['message'] = "验证码有误";
            }
        }
        return $this->json($return, 200);
    }

    /**
     * check verify code
     *
     * @param int phone require phonenumber
     * @param int code require the sms code
     * @param int name require the user's name
     */
    public function checkCodeAction(Request $request)
    {
        $return['errno'] = 1;
        $return['message'] = "验证码已过期";

        $phone = intval($request->get('phone'));
        $code = intval($request->get('code'));
        $content = $request->get('content');
        $name = $request->get('name');
        $verify = $_SESSION['code'];

        if (!$name || !$phone || !$code) {
            $return['errno'] = 3;
            $return['message'] = "数据不全";
        } else {
            if ($verify && $verify['created_at'] > time()) {
                if ($verify['code'] == $code && $verify['phone'] == $phone) {
                    //store the user info to database
                    $return['errno'] = 0;
                    $return['message'] = "成功";
                } else {
                    $return['errno'] = 2;
                    $return['message'] = "验证码或手机号码不正确";
                }
            }
        }

        return $this->json($return, 200);
    }

    /**
     * store page info
     *
     * @param int phone require phonenumber
     * @param int code require the sms code
     * @param int name require the user's name
     */
    public function storePageAction(Request $request)
    {
        $Id=$request->get('id','');
        $em = $this->getDoctrine()->getManager();
        if($Id){
            $page = $em->getRepository('AppBundle:Pages')->find($Id);
        } else {
            $page = new Pages();
        }
        $category = $em->getRepository('AppBundle:Category')->find($_REQUEST['category']);
        $images = implode(';',json_decode($_REQUEST['images'],true));

        $page->setName($_REQUEST['title']);
        $page->setPicurl($_REQUEST['picurl']);
        $page->setPcContent($_REQUEST['pchtml']);
        $page->setPcCss($_REQUEST['pccss']);
        $page->setPcJs($_REQUEST['pcjs']);
        $page->setMContent($_REQUEST['mhtml']);
        $page->setMCss($_REQUEST['mcss']);
        $page->setMJs($_REQUEST['mjs']);
        $page->setCreatedAt(time());
        $page->setActive($_REQUEST['active']);
        $page->setCategory($category);
        $page->setSort($_REQUEST['sort']);
        $page->setPcCssImport($_REQUEST['pccssimport']);
        $page->setPcJsImport($_REQUEST['pcjsimport']);
        $page->setMCssImport($_REQUEST['mcssimport']);
        $page->setMJsImport($_REQUEST['mjsimport']);
        $page->setImages($images);

        if(!$Id){
            $em->persist($page);
        }
        $em->flush();

        if ($page->getId()) {
            $return['errno'] = 0;
            $return['message'] = "成功";
        } else {
            $return['errno'] = 1;
            $return['message'] = "失败";
        }

        return $this->json($return, 200);
    }

    /**
     * upload file
     *
     */
    public function deletePageAction(Request $request)
    {
        $array = array(
            'errno' =>1,'message'=>'错误'
        );
        try {
            $Id = $request->get('id','');
            $em = $this->getDoctrine()->getManager();
            if($Id){
                $page = $em->getRepository('AppBundle:Pages')->find($Id);
                if($page){
                    //delete images
                    $images = $page->getImages();
                    $all = explode(';', $images);
                    foreach ($all as $key => $value) {
                        if ($value && file_exists('.' . $value)) {
                            unlink('.' . $value);
                        }
                    }
                    if ($page->getPicurl() && file_exists('.' . $page->getPicurl())) {
                        unlink('.' . $page->getPicurl());
                    }
                    $em->remove($page);
                    $em->flush();
                    $array = array(
                        'errno' =>0,'message'=>'成功'
                    );
                } else {
                    $array = array(
                        'errno' =>1,'message'=>'未找到'
                    );
                }
            }
            return $this->json($array, 200);
        } catch (Exception $e) {
            return $this->json(array('errno' => 1,'message'=>'异常'), 400);
        }
    }
}
